import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:get/get.dart';

import 'package:work/entity/game_entity.dart';
import 'package:work/pages/game/game_controller.dart';

final _coinCountProvider = StateProvider.autoDispose<int>((ref) => 0);

final _listProvider = StateProvider((ref) {
  final copyGroups = [
    GameEntity(
      title: 'GoGoMatch',
      description: 'Match Same files 3',
      num: 5,
      imageUrl: '',
      backgroundImageUrl: '',
    ),
    GameEntity(
      title: 'Coin Other',
      description: 'Eliminate 6 times ',
      num: 5,
      imageUrl: '',
      backgroundImageUrl: '',
    ),
    GameEntity(
      title: 'Melon Fusion',
      description: 'Score 15000 Points',
      num: 25,
      imageUrl: '',
      backgroundImageUrl: '',
    ),
    GameEntity(
      title: 'GoGoMatch',
      description: 'Match Same files 3',
      num: 5,
      imageUrl: '',
      backgroundImageUrl: '',
    ),
    GameEntity(
      title: 'Coin Other',
      description: 'Eliminate 6 times ',
      num: 5,
      imageUrl: '',
      backgroundImageUrl: '',
    ),
    GameEntity(
      title: 'Melon Fusion',
      description: 'Score 15000 Points',
      num: 25,
      imageUrl: '',
      backgroundImageUrl: '',
    ),
  ];

  return copyGroups;
});

class GameTab extends StatefulWidget {
  const GameTab({super.key});

  @override
  State<GameTab> createState() => _GameTabState();
}

class _GameTabState extends State<GameTab> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 12),
        child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: const [
              SizedBox(height: 60),
              _TopNameWidget(),
              _TopCoinWidget(),
              SizedBox(height: 8),
              Text('Play Game'),
              SizedBox(height: 8),
              Expanded(child: GameListWidget()),
            ]),
      ),
    );
  }

  /// 当应用生命周期发生变化时 , 会回调该方法
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    debugPrint("当前的应用生命周期状态 : $state");
    if (state == AppLifecycleState.paused) {
      debugPrint("应用进入后台 paused");
    } else if (state == AppLifecycleState.resumed) {
      debugPrint("应用进入前台 resumed");
      GameController.to.coins.value += 1;
    } else if (state == AppLifecycleState.inactive) {
      // 应用进入非活动状态 , 如来了个电话 , 电话应用进入前台
      // 本应用进入该状态
      debugPrint("应用进入非活动状态 inactive");
    } else if (state == AppLifecycleState.detached) {
      // 应用程序仍然在 Flutter 引擎上运行 , 但是与宿主 View 组件分离
      debugPrint("应用进入 detached 状态 detached");
    }
  }

  /// 移出组件中注册的观察者
  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }
}

class _TopNameWidget extends StatelessWidget {
  /// 头部名称区域
  const _TopNameWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 50,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(color: Colors.red, height: 50, width: 50),
          const SizedBox(width: 10),
          const Text('CatchYoo'),
          const Icon(Icons.arrow_forward_ios),
        ],
      ),
    );
  }
}

class _TopCoinWidget extends GetView<GameController> {
  /// 头部金钱区域
  const _TopCoinWidget({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(GameController());
    return _buildTopCoinWidget();
  }

  _buildTopCoinWidget() {
    return Row(
      children: [
        Expanded(child: _buildLeftWidget()),
        const SizedBox(width: 6),
        _buildRightWidget(),
      ],
    );
  }

  _buildLeftWidget() {
    return Container(
      color: Colors.yellow,
      height: 100,
      child: Column(
        children: [
          Container(
            height: 40,
            color: Colors.green,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: const [
                Text('Redeem Rewards'),
                Icon(
                  Icons.arrow_forward_ios,
                  size: 12,
                  color: Colors.white,
                ),
              ],
            ),
          ),
          Row(
            children: [
              Container(width: 60, height: 60, color: Colors.red),
              const SizedBox(width: 12),
              Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text('Google Play'),
                  Row(
                    children: const [
                      Icon(Icons.circle),
                      Text('500'),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }

  _buildRightWidget() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(10),
      child: Container(
        width: 140,
        height: 100,
        color: Colors.blue,
        padding: const EdgeInsets.all(6),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: const [
                Text('My Coinds'),
                Icon(Icons.add),
              ],
            ),
            Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const Icon(Icons.circle),
                  Obx(() {
                    return Text(
                      controller.coins.value.toString(),
                      style: const TextStyle(fontSize: 36),
                    );
                  }),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class GameListWidget extends ConsumerWidget {
  const GameListWidget({super.key});

  @override
  Widget build(BuildContext context, ref) {
    return _buildList(ref, context);
  }

  Widget _buildList(ref, context) {
    final gameList = ref.read(_listProvider);
    return Container(
      color: Colors.blueGrey,
      padding: const EdgeInsets.symmetric(horizontal: 12),
      child: MediaQuery.removePadding(
        context: context,
        removeTop: true,
        child: ListView.separated(
          itemCount: gameList.length,
          itemBuilder: (_, idx) => GameCellWidget(entity: gameList[idx]),
          separatorBuilder: (_, idx) => const SizedBox(height: 12),
        ),
      ),
    );
  }
}

class GameCellWidget extends StatelessWidget {
  final GameEntity entity;
  const GameCellWidget({super.key, required this.entity});

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(16.0),
      child: Container(
        height: 200,
        color: Colors.grey,
        child: Stack(children: [
          Container(color: Colors.red),
          Positioned(
            bottom: 12,
            left: 12,
            right: 12,
            height: 60,
            child: Row(children: [
              Container(
                width: 60,
                height: 60,
                color: Colors.yellow,
              ),
              const SizedBox(width: 4),
              Expanded(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(entity.title),
                    const SizedBox(height: 8),
                    Text(entity.description),
                  ],
                ),
              ),
              GestureDetector(
                  onTap: () {},
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(12),
                    child: Container(
                      width: 80,
                      height: 40,
                      color: Colors.greenAccent,
                      alignment: Alignment.center,
                      child: const Text('Play'),
                    ),
                  ))
            ]),
          )
        ]),
      ),
    );
  }
}
